﻿using System;
using System.Collections.Generic;
using SecurityTokenServiceNS;
using System.Xml.Linq;

namespace RstAddIns
{
	class RSTModuleISIP : IRSTProcessor
	{
		private XNamespace _wsid = Constants.WSIdentity.NamespaceUri;

		//public XNamespace NamespaceUri
		//{
		//    get { return null; }
		//}

		/// <summary>
		/// This method processes the received RST message into a RST object
		/// </summary>
		/// <param name="rst">RST Object</param>
		/// <param name="rst">RST Message</param>
		public void ProcessMessage(RST rst, XElement xRst)
		{
			try
			{
				if (xRst == null)
					throw new ArgumentNullException("xRst");

				if (xRst.IsEmpty)
					throw new ArgumentException("wst:RequestSecurityToken element was empty. Unable to process RST.");

				ProcessInformationCardReference(rst, xRst.Element(_wsid + Constants.WSIdentity.Elements.InformationCardReference));
				ProcessClientPseudonym(rst, xRst.Element(_wsid + Constants.WSIdentity.Elements.ClientPseudonym));
				ProcessStrElement(rst, xRst, _wsid, Constants.WSIdentity.Elements.RequestDisplayToken);
			}
			catch (Exception Ex)
			{
				Console.WriteLine(Ex.Message);
				throw Ex;
			}
		}
		private void ProcessStrElement(RST rst, XElement xe, XNamespace ns, string elemName)
		{
			if (xe.Element(ns + elemName) != null)
				rst.Extensions.Add(elemName, xe.Element(ns + elemName).Value);
		}

		private void ProcessInformationCardReference(RST rst, XElement xICReference)
		{
			if (xICReference != null)
			{
				if (xICReference.IsEmpty)
					throw new ArgumentException("wsid:InformationCardReference element was empty. Unable to add InformationCardReference elements.");
				ProcessStrElement(rst, xICReference, _wsid, Constants.WSIdentity.Elements.CardId);
				ProcessStrElement(rst, xICReference, _wsid, Constants.WSIdentity.Elements.CardVersion);
			}
		}
		private void ProcessClientPseudonym(RST rst, XElement xClientPseudonym)
		{
			if (xClientPseudonym != null)
			{
				if (xClientPseudonym.IsEmpty)
					throw new ArgumentException("wsid:ClientPseudonym element was empty. Unable to add ClientPseudonym elements.");
				ProcessStrElement(rst, xClientPseudonym, _wsid, Constants.WSIdentity.Elements.PPID);
			}
		}

	}
}
